package net.cheyo.mobile;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import net.cheyo.ipaddr.IpAddrQuery;
import net.cheyo.ipaddr.IpLocationBean;
import net.cheyo.ipaddr.IpQueryResultBean;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class MobileQuery
{
    public static Logger logger = Logger.getLogger(MobileQuery.class);

    public static String YOUDO_MOBILE_API_URL_PREFIX = "http://www.youdao.com/smartresult-xml/search.s?type=mobile&q=";

    public int query(String mobileNum, StringBuffer queryResult)
    {
        logger.info("enter");

        HttpClient httpClient = new DefaultHttpClient();
        final String url = YOUDO_MOBILE_API_URL_PREFIX + mobileNum;
        HttpGet httpGet = new HttpGet(url);

        HttpResponse response;
        String responseText;
        
        try
        {
            logger.info("try to get url:" + url);
            response = httpClient.execute(httpGet);
            responseText = EntityUtils.toString(response.getEntity());

            logger.info("response status line: " + response.getStatusLine());
            logger.info("response content: " + responseText);
        }
        catch (ClientProtocolException e)
        {
            logger.error(e);
            queryResult.append("Internal error. Please try it later");
            return 1;
        }
        catch (IOException e)
        {
            logger.error(e);
            queryResult.append("Internal error. Please try it later");
            return 1;
        }

        JAXBContext jaxbContext;
        try
        {
            jaxbContext = JAXBContext.newInstance(IpQueryResultBean.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            IpQueryResultBean ipResult = (IpQueryResultBean) unmarshaller
                    .unmarshal(new StringReader(responseText));

            List<IpLocationBean> ipLocations = ipResult.getIpLocaton();
            if (0 == ipLocations.size())
            {
                queryResult.append("Internal error. Please try it later");
                return 1;
            }
            queryResult.append(ipLocations.get(0).getLocation());

            httpClient.getConnectionManager().shutdown();
        }
        catch (Exception e)
        {
            logger.error(e);
            queryResult.append("Internal error. Please try it later");
            return 1;
        }
        finally
        {
            httpClient.getConnectionManager().shutdown();
        }

        return 0;
    }
}
